const Service = require('egg').Service;
class TestService extends Service {
  async add(data) {
    data = {
      ...data,
      created_time: Date.now(),
      update_time: Date.now(),
    };
    const { ctx } = this;
    const res = await ctx.model.Test.create(data);
    if (res) {
      return {
        code: 0,
        msg: '添加成功',
      };
    }
    return {
      code: 1,
      msg: '添加失败',
    };


  }
  async find(_data) {
    const { ctx } = this;
    const { page, pageSize } = _data;
    if (page <= 0 || pageSize <= 0 || pageSize > 1000) {
      return {
        code: 1,
        msg: '参数不正确,page pageSize必须大于0且pagesize小于等于1000',
      };
    }
    const list = await ctx.model.Test.find().limit(pageSize * 1).skip((page * 1 - 1) * pageSize);
    const total = await ctx.model.Test.count();
    if (list) {
      return {
        code: 0,
        msg: '查询成功',
        data: {
          total,
          list,
        },
      };
    }
  }
  async set(_data) {
    const { ctx } = this;
    const query = {
      _id: _data.id,
    };
    const data = {
      ..._data,
      update_time: Date.now(),
    };
    const res = await ctx.model.Test.updateOne(query, data);
    console.log('res', res);
    return {
      code: 0,
      msg: '修改成功',
    };
  }
  async del(data) {
    const { ctx } = this;
    let res = null;
    if (data.id) {
      // 单个删除
      res = await ctx.model.Test.deleteOne({ _id: data.id });
    } else if (data.ids) {
      // 批量删除
      res = await ctx.model.Test.deleteMany({
        _id: {
          $in: data.ids,
        },
      });
    }
    return {
      code: 0,
      msg: '删除成功',
    };
  }
}
module.exports = TestService;
